package cn.oowoo.rabbitmq.transcation;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: Zhangbin
 * @Date: 2021/5/9 12:26
 * @Description:  事务消息测试 - 生产者
 **/
public class TransactionProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();
        //开启事务
        channel.txSelect();
        try{
            for(int i=0;i<3;i++){
                String msg = "测试transaction消息.... "+i;
                channel.basicPublish("",RabbitConfig.QUEUE_TRANSACTION_NAME,null,msg.getBytes());
                if(i==2){
                    throw new RuntimeException();//模拟一个异常
                }
                System.out.println("消息"+i+"已经发送");
            }
            channel.txCommit();//事务提交
            System.out.println("消息发送完毕，事务已提交");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("出现异常，事务将回滚");
            channel.txRollback();//异常，事务回滚
        }finally {
            //消息发送完毕关闭信道，关闭链接
            channel.close();
            connection.close();
        }
    }
}
